<template>
    <edit-dialog :centerDialogVisible="visible2" tilte="地图选择检查区域" :default-button="false" @Cancel="handleCancel"
        width="1000px" class="addform" style="position: relative;">
        <template #content>
            <div style="position: relative;">
                <map-control style="height: 500px" @mapLoad="mapLoadEvent" @mapClick.once="mapClick"></map-control>
                <div class="leftInfo">
                    <p class="title" style="">检查区域</p>
                    <el-radio-group class="ml-4" v-model="radio">
                        <el-radio label="1" style="margin-left: 13px;">选择本次作业的区域</el-radio>
                        <div class="kuangxuanBox" @click.stop="mapClickItem(1)">
                            <div class="kuangxuan1"></div>
                            <div class="kuangxuan2"></div>
                            <div class="kuangxuan3"></div>
                        </div>
                        <div class="dianxuanBox" @click.stop="mapClickItem(2)">
                            <div class="dianxuan1"></div>
                            <div class="dianxuan2"></div>
                            <div class="dianxuan3"></div>
                            <div class="dianxuan4"></div>
                            <div class="dianxuan5"></div>
                        </div>
                        <el-input placeholder="请输入作业区域名称" style="width: 230px;height: 34px;margin-left: 16px;"
                            show-word-limit v-model="areaName"></el-input>
                        <el-radio label="2" style="margin-left: 13px;"> 全场 </el-radio>
                    </el-radio-group>
                </div>

                <div class="utils">
                    <div class="rangingBox" @click="">
                        <div class="bigRound"></div>
                        <div class="ranging"></div>
                    </div>

                    <div class="zoomUpBox" @click="zoomUP">
                        <div class="bigRound"></div>
                        <div class="smallRound"></div>
                        <div class="zoomUp"></div>
                    </div>

                    <div class="zoomDownBox" @click="zoomDown">
                        <div class="bigRound"></div>
                        <div class="smallRound"></div>
                        <div class="zoomDown"></div>
                    </div>
                </div>

                <div class="changGis">
                    <el-radio-group v-model="layer" class="btn_d btnLayer">
                        <el-radio-button v-for="area in areaDetail" :key="area.buildName" :label="area.buildName"
                            @change.stop="showFloor(area.floorDesc)">
                            {{ area.buildName }}
                        </el-radio-button>
                    </el-radio-group>
                    <el-radio-group v-model="subLayer" v-if="hasSub" class="btn_d subLayer">
                        <el-radio-button v-for="area in subLayers" :key="area.buildName" :label="area.buildName"
                            @change.stop="switchMap(area.name)">
                            {{ area.buildName }}
                        </el-radio-button>
                    </el-radio-group>
                </div>
            </div>
        </template>
        <template #custom>
            <span class="dialog-footer">
                <el-button class="buttonCancel" @click="handleCancel">清空</el-button>
                <el-button type="primary" class="btn-ok" @click="handleAddSubmit">确定</el-button>
            </span>
        </template>

    </edit-dialog>
</template>

<script setup lang="ts">
import editDialog from '@/components/editDialog/index.vue'
import mapControl from '@/components/map/index.vue'
import { store } from "@/components/map/mapStore";
import { areaDetail } from '@/config/config'
import { ElMessage } from 'element-plus';
import { ref, watch } from 'vue';

const radio = ref('1')     //单选框默认选中
const coordinate = ref('');// 框选坐标
let areaName = ref('');    // 作业区域名称
let id = ref(0);           // 编辑状态判定
const layer = ref();       // 用于保存机场层级
const subLayer = ref()     // 用于保存选择的机场子层级
const subLayers = ref([])  // 用于保存机场子层级数组
const hasSub = ref(false)  // 是否显示机场子层级
const vcoordinate = ref([]) as any;
const cjState = ref(true);// 测距按钮状态
const activeWidget = ref(null);// 测距对象
// ----------------------------------    地图相关操作    ----------------------------------------

const showFloor = (val: string[]) => {
    if (val !== undefined) {
        subLayers.value = val
        hasSub.value = true
    } else {
        hasSub.value = false
    }
}

const switchMap = (name: string) => {
    store.BNMap.switchDCJ(name, () => {
        // 一般为调用setCenter和setLevel方法

    })
}

const cj = () => {
    if (cjState.value) {
        activeWidget.value = store.BNMap.addDistanceMeasurement2D();
    } else {
        console.log('activeWidget', activeWidget.value);
        // store.BNMap.delMeasurement2D(activeWidget.value.distance);
        store.BNMap.delMeasurement2D(activeWidget.value);
    }
    cjState.value = !cjState.value
}

const zoomUP = () => {
    store.BNMap.zoomIn();
}

const zoomDown = () => {
    store.BNMap.zoomOut();
}

// 工具栏
const mapClickItem = (label: Number) => {
    try {
        store.BNMap.removeGraphicsLayer('demo');
        store.BASE.cancel();
        drawAreaOnMap([]);
    } catch (error) {
    }
}

let drawLayer;
/**
 * 绘制图形
 * @param val 地图坐标
 * @param data 房屋数据
 */
const drawAreaOnMap = (data) => {
    const drawLayer = store.BNMap.creatGraphicsLayer({ id: 'demo' });
    drawLayer.removeAll();

    if (!Array.isArray(data)) {
        return;
    }
    const coordinate = [];
    data.forEach((item) => {
        coordinate.push([item.latitude, item.longitude]);
    });
    data = coordinate;
    let sectorsym;
    sectorsym = store.BNSymbol.polygonSymbol(
        "solid",
        store.BNSymbol.simpleLineSymbol("solid", "#2F7DF1", 1),
        "#bad4fb"
    );
    // 要素图层
    const polygon = store.BNGeometry.createPolygon({
        rings: data,
        spatialReference: store.BNMap.spatialReference,
    });
    // 绘制颜色层内容
    const sectorGrp = store.BNMap.graphic(polygon, sectorsym);

    // const center = getCenterByGeometry(sectorGrp.geometry)

    // // 设置图层中心点为地图中心点
    // store.BNMap.setCenter(center.x, center.y)

    drawLayer.add(sectorGrp);
    store.BNMap.addGraphicsLayer(drawLayer);
};

// 通过geometry获取中心点
const getCenterByGeometry = (geometryArgs: { rings: any[] }) => {
    // 创建中心点对象
    const centerObject = {}
    // 得到当前要素的上、下、左、右偏移量
    const rings = geometryArgs.rings[0]
    console.log('rings', rings);

    if (rings.length % 2 === 0) {
        centerObject.x = rings[rings.length / 2][0]
        centerObject.y = rings[rings.length / 2][1]
    } else {
        centerObject.x = rings[(rings.length + 1) / 2][0]
        centerObject.y = rings[(rings.length + 1) / 2][1]
    }
    // 返回中心点
    return centerObject
}

const mapLoadEvent = () => {
    ElMessage.success('地图加载成功');
    drawAreaOnMap(vcoordinate.value);
}

const mapClick = () => {
    draw("polygon");
};
const draw = (type: string) => {
    // "point"：点、"line"：线、"freeline"：自由线、 "polygon"：面
    // "circle"：圆、"curve"：弧线、"freehandarrow"：箭头、"multihead"：多箭头、"beziercurve"：bezier线、"bezierpolygon"：bezier面
    // drawMap();
    // tool.activate(type);
    //以上两句为原始绘画代码
    store.BASE.polygon();
};

// 用来输出画图后对应的坐标点集合,参数值来自于Map.html
const myRings = ref();
function bnSketchComplete(rings: any) {
    // 自行添加坐标值的处理代码
    myRings.value = rings;
    let itemArr = rings[0].map(item => {
        return { latitude: item[0], longitude: item[1] }
    })
    coordinate.value = JSON.stringify(itemArr);
}
// 用来确保Map.html能够调用该页面的bnSketchComplete方法并返回参数
window["bnSketchComplete"] = (rings: any) => {
    bnSketchComplete(rings);
};

setTimeout(() => {
    watch(() => props.echoData, (newValue: any, oldValue: any) => {
        if (Object.keys(newValue).length > 0) {
            id.value = newValue.id;
            areaName.value = newValue.areaName;
            vcoordinate.value = JSON.parse(newValue.coordinate)
        }
    })
}, 500)

const props = defineProps({
    visible2: {
        type: Boolean,
        default: false,
    },
    echoData: {
        type: Object,
        defult: () => []
    }
})
const emit = defineEmits(['cancel', 'mapDate']);

//清空绑定值
const handleCancel = () => {
    clearData();
    emit('cancel')
}

// 清空地图相关数据
const clearData = () => {
    id.value = 0;
    areaName.value = '';
    coordinate.value = '';
    vcoordinate.value = [];
    cjState.value = true;
    try {
        store.BNMap.removeGraphicsLayer('demo')
        store.BASE.cancel()
    } catch (error) {
    }
}

const handleAddSubmit = async (formEl: any) => {
    try {
        if (areaName.value == '') {
            ElMessage.error('请输入检查区域名称!');
            return
        }

        if (coordinate.value == '' && JSON.stringify(vcoordinate.value) == '[]') {
            ElMessage.error('请框选作业区域!');
            return
        }
        console.log('绘制数据', coordinate.value);

        setTimeout(() => {
            if (coordinate.value != '') {
                emit('mapDate', { coordinate: coordinate.value, areaName: areaName.value, id: id.value })
            } else {
                emit('mapDate', { coordinate: JSON.stringify(vcoordinate.value), areaName: areaName.value, id: id.value })
            }
            clearData();
            emit('cancel');
        }, 500);

    } catch (error) {
    }
}
</script>

<style scoped>
.leftInfo {
  position: absolute;
  top: 10px;
  left: 6px;
  z-index: 999;
  height: 300px;
  width: 260px;
  border-radius: 5px;
  background: #fff;
  padding-left: 4px;
  .title {
    color: #353a42;

    /* margin-left: 2px; */
    padding: 12px;
    font-size: 12px;
    font-weight: bold;
  }
  .kuangxuanBox {
    .kuangxuan1 {
      position: absolute;
      top: 52px;
      left: 168px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/kuangxuan1.svg') no-repeat;
    }
    .kuangxuan2 {
      position: absolute;
      top: 52px;
      left: 168px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/kuangxuan2.svg') no-repeat;
    }
    .kuangxuan3 {
      position: absolute;
      top: 52px;
      left: 168px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/kuangxuan3.svg') no-repeat;
    }
  }
  .dianxuanBox {
    .dianxuan1 {
      position: absolute;
      top: 53px;
      left: 200px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/dianxuan1.svg') no-repeat;
    }
    .dianxuan2 {
      position: absolute;
      top: 52px;
      left: 204px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/dianxuan2.svg') no-repeat;
    }
    .dianxuan3 {
      position: absolute;
      top: 52px;
      left: 200px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/dianxuan3.svg') no-repeat;
    }
    .dianxuan4 {
      position: absolute;
      top: 64px;
      left: 210px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/dianxuan1.svg') no-repeat;
    }
    .dianxuan5 {
      position: absolute;
      top: 62px;
      left: 212px;
      width: 20px;
      height: 20px;
      background: url('../../../../../public/imgs/dianxuan2.svg') no-repeat;
    }
  }
}
.bigRound {
  width: 36px;
  height: 36px;
  background: url('../../../../../public/imgs/bigRound.svg') no-repeat;
}
.smallRound {
  position: absolute;
  top: 10px;
  right: 6px;
  width: 20px;
  height: 20px;
  background: url('../../../../../public/imgs/smallRound.svg') no-repeat;
}
.utils {
  .rangingBox {
    position: absolute;
    top: 40px;
    right: 20px;
    .ranging {
      position: absolute;
      top: 1px;
      width: 36px;
      height: 36px;
      background: url('../../../../../public/imgs/ranging.svg') no-repeat center center;
    }
  }
  .zoomUpBox {
    position: absolute;
    top: 86px;
    right: 20px;
    .zoomUp {
      position: absolute;
      top: 1px;
      width: 36px;
      height: 36px;
      background: url('../../../../../public/imgs/zoomUp.svg') no-repeat center center;
    }
  }
  .zoomDownBox {
    position: absolute;
    top: 130px;
    right: 20px;
    .zoomDown {
      position: absolute;
      top: 1px;
      width: 36px;
      height: 36px;
      background: url('../../../../../public/imgs/zoomDown.svg') no-repeat center center;
    }
  }
}
.changGis {
  .btn_d {
    right: 20px;
    bottom: 0;
  }
  .btnLayer {
    position: absolute;
    bottom: 10px;
    border: 0;
    transition: left 1s;
    transition-timing-function: linear;
  }
  .subLayer {
    position: absolute;
    width: 30px;
    bottom: 50px;
    border: 0;
  }
  .subLayer /deep/ .el-radio-button .el-radio-button__inner {
    width: 30px;
    border: 1px #fff solid;
    padding: 10px;
  }
  .subLayer /deep/ .el-radio-button:first-child .el-radio-button__inner {
    border-radius: 6px 6px 0 0;
  }
  .subLayer /deep/ .el-radio-button:last-child .el-radio-button__inner {
    border-radius: 0 0 6px 6px;
  }


}
::v-deep(.el-radio) {
  margin-right: 1.2rem;
}
</style>
